<?php
/**
 * 客户收藏/取消收藏操作
 */

namespace App\Http\Controllers\Api\V1\App\Customers;

use App\Http\Controllers\ApiController;
use App\Models\Customers\Customer;
use App\Models\Customers\CustomerWishList;
use App\Models\Products\Product;
use App\Services\Repositories\ProductRepository;
use App\Services\Utils\Guard;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;

class CustomerWishListController extends ApiController
{
    private $productRepository;

    public function __construct(ProductRepository $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    /**
     * App个人中心，收藏商品列表信息
     *
     * @param Request $request
     * @return array|\Illuminate\Http\Response
     */
    public function index(Request $request )
    {
        $products = $this->productRepository->getCustomerWishProducts($request);

        return $this->response(compact('products'));
    }

    /**
     * 收藏商品
     * @param Request $request
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function store(Request $request)
    {
        $customer = Guard::customer();

        $product = $this->productRepository->findOnShelfProductOrFailed($request->product_id);

        $wish = (new CustomerWishList())->firstOrCreate([
            'customer_id' => $customer->customer_id,
            'product_id'  => $product->product_id,
        ], [
            'date_added' => (string)now(),
        ]);

//        $is_wish_product = Customer::isProductInWishList($product);
        $is_wish_product = true;

        return $this->response(compact('wish', 'is_wish_product'));
    }

    /**
     * 取消收藏
     * @param $product_id
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function destroy($product_id)
    {
        $customer = Guard::customer();

        $product = $this->productRepository->findOnShelfProductOrFailed($product_id);

        $remove = (new CustomerWishList())->where([
            ['customer_id', $customer->customer_id],
            ['product_id', $product->product_id],
        ])->delete();

        $is_wish_product = $customer->isProductInWishList($product);

        return $this->response(compact('remove', 'is_wish_product'));
    }
}